/*
 * Copyright (c) 2020 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.surina.soundtouch.slice;

import net.surina.soundtouch.ResourceTable;
import net.surina.soundtouch.util.LogUtil;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;

import ohos.agp.components.Button;
import ohos.agp.components.Text;

import ohos.media.common.Source;
import ohos.media.player.Player;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import static net.surina.soundtouch.util.ResUtil.AUDIO_OUTPUT_PATH;

public class AudioClientSlice extends AbilitySlice implements Player.IPlayerCallback {
    private static final String TAG = AudioClientSlice.class.getSimpleName();

    private Player player;
    private Button playButton;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_audio_play_layout);
    }

    @Override
    protected void onActive() {
        super.onActive();

        Text uriText = (Text) findComponentById(ResourceTable.Id_input_uri);
        playButton = (Button) findComponentById(ResourceTable.Id_play_button);
        uriText.setText(AUDIO_OUTPUT_PATH);

        File file = new File(AUDIO_OUTPUT_PATH); // Specify the requied media file path.
        FileInputStream in = null;
        FileDescriptor fd = null;
        try {
            in = new FileInputStream(file);
            fd = in.getFD(); // Obtain the file descriptor object from the input stream.
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        FileDescriptor finalFd = fd;
        playButton.setClickedListener(component -> play(finalFd, playButton));
    }

    private void play(FileDescriptor fd, Button playButton) {
        if (player == null || !player.isNowPlaying()) {
            if (!fd.valid()) {
                LogUtil.warn(TAG, "input uri is empty.");
                return;
            }
            if (player != null) {
                player.release();
            }
            player = new Player(this);
            player.setPlayerCallback(this);
            Source source = new Source(fd);
            if (!player.setSource(source)) {
                LogUtil.warn(TAG, "uri is invalid");
                return;
            }
            if (!player.prepare()) {
                LogUtil.warn(TAG, "prepare failed");
                return;
            }
            if (!player.play()) {
                LogUtil.warn(TAG, "play failed");
                return;
            }
            playButton.setText(ResourceTable.String_pause);
        } else {
            if (player != null) {
                player.stop();
                player.release();
            }
            playButton.setText(ResourceTable.String_play);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        release();
    }

    private void release() {
        if (player != null) {
            player.stop();
            player.release();
        }
    }

    @Override
    protected void onBackPressed() {
        LogUtil.info(TAG, "onBackPressed");
        super.onBackPressed();
        if (player != null) {
            player.stop();
            player.release();
        }
        playButton.setText(ResourceTable.String_play);
    }

    @Override
    public void onPrepared() {

    }

    @Override
    public void onMessage(int i, int i1) {

    }

    @Override
    public void onError(int i, int i1) {
        LogUtil.info(TAG, "onError");
    }

    @Override
    public void onResolutionChanged(int i, int i1) {

    }

    @Override
    public void onPlayBackComplete() {
        getUITaskDispatcher().asyncDispatch(() -> {
            LogUtil.info(TAG, "onPlayBackComplete");
            playButton.setText(ResourceTable.String_play);
        });
    }

    @Override
    public void onRewindToComplete() {

    }

    @Override
    public void onBufferingChange(int i) {

    }

    @Override
    public void onNewTimedMetaData(Player.MediaTimedMetaData mediaTimedMetaData) {

    }

    @Override
    public void onMediaTimeIncontinuity(Player.MediaTimeInfo mediaTimeInfo) {

    }
}
